package cn.virens.web.components.shiro.oauth2.filter;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;

import cn.hutool.core.util.StrUtil;
import cn.virens.oauth2.Oauth2Client;
import cn.virens.oauth2.standard.Oauth2AuthorizeBuilder;
import cn.virens.util.Assert;

public class Oauth2UserFilter extends UserFilter {

	private Boolean useSsl = false;

	private Oauth2Client oauth2Request;

	public Boolean getUseSsl() {
		return useSsl;
	}

	public void setUseSsl(Boolean useSsl) {
		this.useSsl = useSsl;
	}

	public Oauth2Client getOauth2Request() {
		return oauth2Request;
	}

	public void setOauth2Request(Oauth2Client oauth2Request) {
		this.oauth2Request = oauth2Request;
	}

	/**
	 * 重定向到登录页
	 */
	@Override
	protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
		Assert.isNull(oauth2Request, "Oauth2RequestClient is null");

		// 构建Oauth2认证地址
		Oauth2AuthorizeBuilder authorizeBuilder = oauth2Request.authorize();
		authorizeBuilder.setRedirectUri(getLoginUrl(WebUtils.toHttp(request)));
		authorizeBuilder.setScope("snsapi_userinfo");

		// 重定向到登录地址
		WebUtils.issueRedirect(request, response, authorizeBuilder.build());
	}

	private String getLoginUrl(HttpServletRequest http) {
		String url = getLoginUrl();

		if (!StrUtil.startWith(url, "http")) {
			String host = http.getHeader("Host");

			if (Boolean.TRUE.equals(useSsl)) {
				return "https://" + host + url(url);
			} else {
				return "http://" + host + url(url);
			}
		} else {
			return url;
		}
	}

	private String url(String url) {
		return StrUtil.startWith(url, '/') ? url : ("/" + url);
	}
}
